package admin

import (
	"bbs-go/internal/models"
	"bbs-go/internal/models/constants"
	"bbs-go/internal/pkg/config"
	"bbs-go/internal/pkg/errs"
	"bbs-go/internal/pkg/uploader"
	"fmt"
	"io"
	"log/slog"
	"strconv"

	"github.com/kataras/iris/v12"
	"github.com/mlogclub/simple/web"
	"github.com/mlogclub/simple/web/params"

	"bbs-go/internal/services"
)

type ResourcesController struct {
	Ctx iris.Context
}

func (c *ResourcesController) PostUpload() *web.JsonResult {
	user := services.UserTokenService.GetCurrent(c.Ctx)
	if user == nil {
		return web.JsonError(errs.NotLogin)
	}

	name := c.Ctx.PostValue("name")
	if name == "" {
		return web.JsonError(fmt.Errorf("请输入文件名"))
	}

	description := c.Ctx.PostValue("description")
	if description == "" {
		return web.JsonError(fmt.Errorf("请输入文件描述"))
	}

	types := c.Ctx.PostValueIntDefault("types", 0)

	file, header, err := c.Ctx.FormFile("file")
	if err != nil {
		return web.JsonError(err)
	}
	defer file.Close()

	if header.Size > constants.UploadMaxBytes {
		return web.JsonErrorMsg("图片不能超过" + strconv.Itoa(constants.UploadMaxM) + "M")
	}

	contentType := header.Header.Get("Content-Type")
	fileBytes, err := io.ReadAll(file)
	if err != nil {
		return web.JsonError(err)
	}

	slog.Info("上传文件：", slog.Any("filename", header.Filename), slog.Any("size", header.Size))
	path := uploader.GenerateFileKey(header.Filename)
	url, err := uploader.PutObject(path, fileBytes, contentType)
	if err != nil {
		return web.JsonError(err)
	}
	cover := c.Ctx.PostValue("cover")
	err = services.ResourcesService.Create(&models.Resources{
		Name:        name,
		Description: description,
		FilePath:    path,
		FileName:    header.Filename,
		Types:       types,
		Cover:       cover,
		Sort:        1,
		Status:      1,
	})
	if err != nil {
		return web.JsonError(err)
	}

	return web.NewEmptyRspBuilder().Put("url", url).JsonResult()
}

func (c *ResourcesController) AnyList() *web.JsonResult {
	list, paging := services.ResourcesService.FindPageByParams(params.NewQueryParams(c.Ctx).EqByReq("types").LikeByReq("name").LikeByReq("description").PageByReq().Desc("id"))
	for i, _ := range list {
		list[i].FilePath = config.Instance.Uploader.Local.Host + list[i].FilePath
	}

	return web.JsonData(&web.PageResult{Results: list, Page: paging})
}

func (c *ResourcesController) Delete() *web.JsonResult {
	id, _ := params.FormValueInt64(c.Ctx, "id")
	if id <= 0 {
		return web.JsonError(fmt.Errorf("请输入id"))
	}
	resource := services.ResourcesService.Get(id)
	if resource == nil {
		return web.JsonError(fmt.Errorf("资源不存在"))
	}

	err := services.ResourcesService.Delete(resource.Id)
	if err != nil {
		return web.JsonError(err)
	}

	err = uploader.DeleteObject(resource.FilePath)
	if err != nil {
		return web.JsonError(err)
	}

	return web.JsonSuccess()
}
